// components/search/index.js
import { KeywordModel } from '../../models/keyword.js'
import { BookModel } from '../../models/book.js'
import { paginationBev } from '../behaviors/pagination.js'

const keywordModel = new KeywordModel()
const bookModel = new BookModel()

Component({
  behaviors: [paginationBev],
  /**
   * 组件的属性列表
   */
  properties: {
    isMore: {
      type: Boolean,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    isSearch: false,
    inputValue: '',
    loadingCenter: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore () {
      if (!this.isLocked()) {
        if (this.hasMoreData()) {
          this.setLocked(true)
          bookModel.searchBook(this.getCurrentStart(), this.data.inputValue).then(res => {
            this.setMoreData(res.books)
            this.setLocked(false)
          }, () => {
            this.setLocked(false)
          })
        }
      }
    },
    handleCancel (e) {
      this.triggerEvent('on-cancel', {
        isSearchShow: false
      }, {})
    },
    handleConfirm (e) {
      const { value, text } = e.detail
      let q = value || text
      keywordModel.setHistory(q)
      this._showLoadingCenter()
      this._showResult()
      this.setData({
        inputValue: q
      })
      bookModel.searchBook(0, q).then(res => {
        this._hideLoadingCenter()
        this.setMoreData(res.books)
        this.setTotal(res.total)
      })
    },
    handleClear (e) {
      this.setData({
        inputValue: ''
      })
      this._hideResult()
      this.clearData()
    },
    _showResult () {
      this.setData({
        isSearch: true
      })
    },
    _hideResult () {
      this.setData({
        isSearch: false
      })
    },
    _showLoadingCenter () {
      this.setData({
        loadingCenter: true
      })
    },
    _hideLoadingCenter () {
      this.setData({
        loadingCenter: false
      })
    }
  },

  attached () {
    this.setData({
      historyWords: keywordModel.getHistory()
    })
    keywordModel.getHot().then(res => {
      this.setData({
        hotWords: res.hot
      })
    })
  }
})
